import { Injectable } from '@angular/core';
import { DialogXWService } from "./dialog.service";
import { Http } from "@angular/http";

@Injectable()
export class DomHelperService {

  constructor(private ds: DialogXWService,private http: Http) { }

  DownLoad(fileurl:string){
    if(!fileurl){
      this.ds.Alert('文件不存在或已删除！');
      return;
    }

    // const res = await this.http.head(fileurl).toPromise();
    // if(!res.ok) return;

    let a:any = document.createElement("a");
    a.href = fileurl;
    a.download ="";
    a.target = "_blank";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }

  /** 
   * Post下载文件
   * 
   * url : 请求地址 
   * */
  PostDownLoad(url:string,formdata:any) {
    let form:any = document.createElement("form");
    form.style.display = "none";
    form.target = "_blank";
    form.method = "post";
    form.action = url;
    document.body.appendChild(form);

    if (formdata) {
      for (var i in formdata) {
        if (!formdata[i]) continue;
        if (Object.prototype.toString.call(formdata[i]) === '[object Array]') {
          var arr = formdata[i];
          for (var j in arr) {
            let input:any = document.createElement("input");
            input.type = "hidden";
            input.name = i;
            input.value = arr[j];
            form.appendChild(input);
          }
        }
        else {
          let input:any = document.createElement("input");
          input.type = "hidden";
          input.name = i;
          input.value = formdata[i];
          form.appendChild(input);
        }
      }
    }
   
    form.submit();
    document.body.removeChild(form);
  }
}
